package gwt.bbsbot.server;

import gwt.bbsbot.client.GreetingService;
import gwt.bbsbot.client.beans.QuestionDataBean;
import gwt.bbsbot.server.entity.QuestionDataEntity;
import gwt.bbsbot.server.pmf.PMF;
import gwt.bbsbot.server.twitter.TwitterManager;
import gwt.bbsbot.server.twitter.beans.TweetBean;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {

	@Override
	public String addQuestion(String name, String question_data, String genre) {
		
		QuestionDataEntity data = new QuestionDataEntity(name, question_data, null, genre);
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			pm.makePersistent(data);
		}finally{
			pm.close();
		}
		return "OK! create data!";
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<QuestionDataBean> getAllQuestions() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String query = "select from " + QuestionDataEntity.class.getName();

		List<QuestionDataEntity> datas = (List<QuestionDataEntity>) pm
				.newQuery(query).execute();
		List<QuestionDataBean> result = new ArrayList<QuestionDataBean>();
		for (QuestionDataEntity data : datas) {
			result.add(new QuestionDataBean(
					data.getId(),
					data.getDay().getTime(),
					data.getName(), 
					data.getQuestionData(),
					data.getProfileImageURL(),
					data.getGenre()));
		}
		return result;
	}

	@Override
	public List<String> getMentions() {
		
		TwitterManager tm = new TwitterManager();
		List<TweetBean> list = tm.search();
		List<String> result = new ArrayList<String>();
		for(TweetBean bean : list){
			result.add(bean.toString());
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<QuestionDataBean> getQuestionsByGenre(String genre) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String query = "select from " + QuestionDataEntity.class.getName() + " where genre == '" + genre + "'";

		List<QuestionDataEntity> datas = (List<QuestionDataEntity>) pm
				.newQuery(query).execute();
		List<QuestionDataBean> result = new ArrayList<QuestionDataBean>();
		for (QuestionDataEntity data : datas) {
			result.add(new QuestionDataBean(
					data.getId(),
					data.getDay().getTime(),
					data.getName(), 
					data.getQuestionData(),
					data.getProfileImageURL(),
					data.getGenre()));
		}
		return result;
	}
}
